package com.gzu.shop.base;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gzu.shop.common.Result;
import com.gzu.shop.common.ResultStatus;
import com.gzu.shop.constant.MessageConstant;
import com.gzu.shop.exception.BaseException;
import com.gzu.shop.param.SearchCondition;
import com.gzu.shop.util.ObjectPropertyUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Clown
 */

@Tag(name = "CRUD功能接口")
@Slf4j

public class BaseController<S extends IService<E>, E> {


    @Parameter(description = "使用protected使得子类能够访问" +
            "使用动态多态绑定子类service")
    @Autowired(required = false)
    protected S baseService;

    @Operation(summary = "实现单个查找")
    @GetMapping("/getById/{id}")
    public Result<E> getById(@PathVariable Integer id) {
        return Result.success(ResultStatus.SUCCESS, baseService.getById(id));
    }

    @Operation(summary = "实现添加功能")
    @PostMapping("/add")
    public Result<Void> addEntity(@RequestBody E entity) {
        baseService.save(entity);
        return Result.success(ResultStatus.SUCCESS);
    }

    @Operation(summary = "实现通过id删除功能")
    @DeleteMapping("/del/{id}")
    public Result<Void> deleteById(@PathVariable Long id) {
        baseService.removeById(id);
        return Result.success(ResultStatus.SUCCESS);
    }

    @Operation(summary = "实现批量删除功能")
    @DeleteMapping("/deleteBatch")
    public Result<Void> deleteBatch(@RequestBody List<Long> ids) {
        System.out.println(ids);
        baseService.removeBatchByIds(ids);
        return Result.success(ResultStatus.SUCCESS);
    }

    @Operation(summary = "实现批量查询功能")
    @PostMapping("/selectBatch")
    public Result<List<E>> selectBatch(@RequestBody List<Long> ids) {
        if (ids.isEmpty()) {
            throw new BaseException(MessageConstant.DATA_IS_NULL);
        }
//        System.out.println(ids);
        return Result.success(ResultStatus.SUCCESS, baseService.listByIds(ids));
    }


    @Operation(summary = "实现编辑实体功能")
    @PostMapping("/edit")
    public Result<Void> editById(@RequestBody E entity) {
        baseService.updateById(entity);
        return Result.success(ResultStatus.SUCCESS);
    }


    @Operation(summary = "实现分页查询功能")
    @PostMapping("/page/{startPage}/{pageSize}")
    public Result<IPage<E>> page(@PathVariable int startPage, @PathVariable int pageSize,
                                 @RequestBody(required = false) SearchCondition<E> searchCondition) {

        QueryWrapper<E> queryWrapper = new QueryWrapper<>();

        queryWrapper = geteQueryWrapper(searchCondition, queryWrapper);
//        log.info("queryWrapper:{}", queryWrapper);

        return Result.success(ResultStatus.SUCCESS, baseService.page(Page.of(startPage, pageSize), queryWrapper));
    }


    @Operation(summary = "实现所有实体功能")
    @PostMapping("/searchAll")
    public Result<List<E>> searchAll(@RequestBody(required = false) SearchCondition<E> searchCondition) {

        QueryWrapper<E> queryWrapper = new QueryWrapper<>();

        queryWrapper = geteQueryWrapper(searchCondition, queryWrapper);
//        log.info("queryWrapper:{}", queryWrapper);


        return Result.success(ResultStatus.SUCCESS, baseService.list(queryWrapper));
    }

    private QueryWrapper<E> geteQueryWrapper(@RequestBody(required = false) SearchCondition<E> searchCondition, QueryWrapper<E> queryWrapper) {
//        searchCondition.getOrders().get(0).
        if (ObjectUtil.isNotEmpty(searchCondition)) {
            // 精确搜索
            if (ObjectUtil.isNotEmpty(searchCondition.getFilter())) {
                queryWrapper = new QueryWrapper<>(searchCondition.getFilter());
            }
            // 拼接模糊搜索
            if (ObjectUtil.isNotEmpty(searchCondition.getSearch())) {

                Map<String, Object> map = ObjectPropertyUtil.getNoNullProperty(searchCondition.getSearch());

                Set<Map.Entry<String, Object>> entries = map.entrySet();

                for (Map.Entry<String, Object> entry : entries) {
                    queryWrapper.or().like(entry.getKey(), entry.getValue());
                }
            }


            // 提取排序字段
            List<SearchCondition.Order> orders = searchCondition.getOrders();
            if (ObjectUtil.isNotEmpty(orders)) {
                for (SearchCondition.Order order : orders) {
                    // 字段转化为驼峰命名法
                    queryWrapper.orderBy(true, order.isAsc(), StrUtil.toUnderlineCase(order.getColumn()));
                }
            }

        }
        return queryWrapper;
    }

}
